package wechat

import (
	"crypto/tls"
	"fmt"
	"github.com/astaxie/beego/logs"
	"io/ioutil"
	"net/http"
	"strings"
)

// 发送微信模板消息
func SendTemplateMsg(key string, content string) string {
	accessToken := GetAccessToken(key)
	url := fmt.Sprintf("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=%s", accessToken)
	req, _ := http.NewRequest("POST", url, strings.NewReader(content))
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	tr := &http.Transport{
		TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
	}
	client := &http.Client{Transport: tr}
	resp, err := client.Do(req)
	if err != nil {
		logs.Error("send wechat template message request fail:", err)
		return ""
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		logs.Error("can not read from wechat template message response:", err)
		return ""
	}
	return string(body)
}